<script setup lang="tsx">
import { computed, nextTick, ref, watch } from 'vue';
import { SimpleScrollbar } from '@sa/materials';
import { useForm, useFormRules } from '@/hooks/common/form';
import { $t } from '@/locales';
import { enableStatusOptions, menuIconTypeOptions, menuTypeOptions } from '@/constants/business';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { getLocalIcons } from '@/utils/icon';
import { fetchGetAllRoles } from '@/service/api';
import {
  getLayoutAndPage,
  getPathParamFromRoutePath,
  getRoutePathByRouteName,
  getRoutePathWithParam,
  transformLayoutAndPageToComponent
} from './shared';
import { ApiMenuInput, ApiMenuItem, ApimenuserviceApi, MenuOpenType, PgType } from '@/api-services';
import { NetoKit } from '@/typings/neto';
import { feature, getAPI } from '@/axios-utils';
import { queryDone } from '@/utils/api';

defineOptions({
  name: 'MenuOperateModal'
});

export type OperateType = UI.TableOperateType | 'addChild';

interface Props {
  /** the type of operation */
  operateType: OperateType;
  /** the edit menu data or the parent menu data when adding a child menu */
  rowData?: ApiMenuItem | null;
  /** all pages */
  allPages: string[];
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: $t('page.manage.menu.addMenu'),
    addChild: $t('page.manage.menu.addChildMenu'),
    edit: $t('page.manage.menu.editMenu')
  };
  return titles[props.operateType];
});

type Model = NetoKit.IsNonNullable<ApiMenuInput> & {
  query: NonNullable<Api.SystemManage.Menu['query']>;
  page: string;
}

const model = ref(createDefaultModel());


function createDefaultModel(): Model {
  return {
    pgType: 0 as unknown as PgType,
    query: [], // 初始化为空数组
    page: '',
    name: '', // 根据 ApiMenuInput 推断添加
    isEnable: true, // 根据 ApiMenuInput 推断添加
    urlKey: '', // 根据 ApiMenuInput 推断添加
    url: '', // 根据 ApiMenuInput 推断添加
    area: 'Api',
    menuPCode: 'Api',
    id: 0,
    code: '',
    urlPars: '',
    i18nKey: '',
    icon: '',
    sort: 0,
    remark: '',
    openType: MenuOpenType.NUMBER_0,
    href: '',
    isHideMenu: false,
    isHideRole: false,
    isManualAdd: false,
    isDeveloper: false,
    isMenu: false,
    isSystem: false,
    isPermission: true,
  };
}

type RuleKey = Extract<keyof Model, 'name' | 'isEnable' | 'urlKey' | 'url' | 'code'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  code: defaultRequiredRule,
  name: defaultRequiredRule,
  isEnable: defaultRequiredRule,
  urlKey: defaultRequiredRule,
  url: defaultRequiredRule,
};

const disabledMenuType = computed(() => props.operateType === 'edit');




/** - add a query input */
function addQuery(index: number) {
  model.value.query.splice(index + 1, 0, {
    key: '',
    value: ''
  });
}

/** - remove a query input */
function removeQuery(index: number) {
  model.value.query.splice(index, 1);
}

async function handleInitModel() {
  //初始化默认model
  model.value = createDefaultModel();

  if (!props.rowData) return;

  await nextTick();

  if (props.operateType === 'addChild') {
    const { code, area, urlKey } = props.rowData;

    Object.assign(model.value, { menuPCode: code, area: area, urlKey: `${urlKey}_child` });
  }

  if (props.operateType === 'edit') {
    const { urlPars, ...rest } = props.rowData;
    const query: NonNullable<Api.SystemManage.Menu['query']> = [];
    //解析参数
    if (urlPars) {
      //获取问号以后的数据,并且以&分隔每一个,添加到query变量中
      urlPars.split('&').forEach(item => {
        const key = item.split('=')[0];
        const value = item.split('=')[1];
        query.push({
          key,
          value
        });
      });
    }
    console.log(urlPars, query)


    Object.assign(model.value, rest);
  }

  if (!model.value.query) {
    model.value.query = [];
  }

}

function closeModal() {
  visible.value = false;
}

function handleUpdateRoutePathByRouteName() {
  if (model.value.urlKey) {
    model.value.url = getRoutePathByRouteName(model.value.urlKey);
  } else {
    model.value.url = '';
  }
}

function handleUpdateI18nKeyByRouteName() {
  if (model.value.urlKey) {
    model.value.i18nKey = `route.${model.value.urlKey}` as App.I18n.I18nKey;
  } else {
    model.value.i18nKey = '';
  }
}

function getSubmitParams() {
  const { ...params } = model.value;

  // const component = transformLayoutAndPageToComponent(layout, page);
  // const routePath = getRoutePathWithParam(model.value.routePath, pathParam);

  // params.component = component;
  // params.routePath = routePath;

  return params;
}

async function handleSubmit() {
  await validate();

  const params = getSubmitParams();

  //设置参数
  console.log('params: ', params);
  const urlPars: string[] = [];
  let result = '';
  params.query.forEach(element => {
    if (element.key) {
      urlPars.push(`${element.key}=${element.value}`)
    }
  });
  if (urlPars.length > 0) {
    result = `${urlPars.join('&')}`
  }
  model.value.urlPars = result;

  //判断是哪一种操作
  switch (props.operateType) {
    case 'add':
      await add();
      break;
    case 'addChild':
      await add();
      break;
    case 'edit':
      await update();
      break;
  }

  // request
  emit('submitted');
}
async function add() {
  const [err, res] = await feature(getAPI(ApimenuserviceApi).insert(model.value));
  queryDone(err, () => {
    if (res?.data.data) {
      window.$message?.success($t('common.success'));
      closeModal();

    } else {
      window.$message?.error($t('common.failed'));

    }
  });
}
async function update() {
  const [err, res] = await feature(getAPI(ApimenuserviceApi).update(model.value));
  queryDone(err, () => {
    if (res?.data.data) {
      window.$message?.success($t('common.success'));
      closeModal();

    } else {
      window.$message?.error($t('common.failed'));

    }
  });
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});

watch(
  () => model.value.urlKey,
  () => {
    handleUpdateRoutePathByRouteName();
    handleUpdateI18nKeyByRouteName();
  }
);
</script>

<template>
  <NModal v-model:open="visible" :title="title" width="800px">
    <div class="h-480px">
      <SimpleScrollbar>
        <ElForm ref="formRef" :model="model" :rules="rules" label-width="auto">
          <ElRow>
            <ElCol :lg="12" :xs="24">
              <ElFormItem :label="$t('page.manage.menu.menuType')" name="menuType">
                <ElRadioGroup v-model="model.pgType" :disabled="disabledMenuType">
                  <ElRadio :key="0" :value="0">
                    {{ $t('page.manage.menu.type.directory') }}
                  </ElRadio>

                  <ElRadio :key="200" :value="200">
                    {{ $t('page.manage.menu.type.menu') }}
                  </ElRadio>
                </ElRadioGroup>
              </ElFormItem>
            </ElCol>
            <ElCol :lg="12" :xs="24">
              <ElFormItem :label="$t('page.manage.menu.menuCode')" name="code">
                <ElInput v-model="model.code" :placeholder="$t('page.manage.menu.form.menuCode')" />
                <!-- :disabled="props.operateType != 'addChild' && props.operateType != 'add'" -->
              </ElFormItem>
            </ElCol>
            <ElCol :lg="12" :xs="24">
              <ElFormItem :label="$t('page.manage.menu.menuPCode')" name="menuPCode">
                <ElInput v-model="model.menuPCode" :placeholder="$t('page.manage.menu.form.menuCode')" />
              </ElFormItem>
            </ElCol>
            <ElCol :lg="12" :xs="24">
              <ElFormItem :label="$t('page.manage.menu.menuName')" name="name">
                <ElInput v-model="model.name" :placeholder="$t('page.manage.menu.form.menuName')" />
              </ElFormItem>
            </ElCol>
            <ElCol :lg="12" :xs="24">
              <ElFormItem :label="$t('page.manage.menu.routeName')" name="urlKey">
                <ElInput v-model="model.urlKey" :placeholder="$t('page.manage.menu.form.routeName')" />
              </ElFormItem>
            </ElCol>
            <ElCol :lg="12" :xs="24">
              <ElFormItem :label="$t('page.manage.menu.routePath')" name="url">
                <ElInput v-model="model.url" disabled :placeholder="$t('page.manage.menu.form.routePath')" />
              </ElFormItem>
            </ElCol>

            <ElCol :lg="12" :xs="24">
              <ElFormItem :label="$t('page.manage.menu.i18nKey')" name="i18nKey">
                <ElInput v-model="(model.i18nKey as string)" :placeholder="$t('page.manage.menu.form.i18nKey')" />
              </ElFormItem>
            </ElCol>
            <ElCol :lg="12" :xs="24">
              <ElFormItem :label="$t('page.manage.menu.order')" name="sort">
                <ElInputNumber v-model="(model.sort as number)" class="w-full"
                  :placeholder="$t('page.manage.menu.form.order')" />
              </ElFormItem>
            </ElCol>
            <ElCol :lg="12" :xs="24">
              <ElFormItem :label="$t('page.manage.menu.icon')" name="icon">
                <ElInput v-model="model.icon" :placeholder="$t('page.manage.menu.form.icon')" class="flex-1">
                  <template #suffix>
                    <SvgIcon v-if="model.icon" :icon="model.icon" class="text-icon" />
                  </template>
                </ElInput>
              </ElFormItem>
            </ElCol>
            <ElCol :lg="12" :xs="24">
              <ElFormItem :label="$t('page.manage.common.isEnable')" name="isEnable">
                <ElRadioGroup v-model="model.isEnable">
                  <ElRadio :value="true">{{ $t('common.yesOrNo.yes') }}</ElRadio>
                  <ElRadio :value="false">{{ $t('common.yesOrNo.no') }}</ElRadio>
                </ElRadioGroup>
              </ElFormItem>
            </ElCol>
            <ElCol :lg="model.openType != 0 ? 12 : 24" :xs="24">
              <ElFormItem :label="$t('page.manage.menu.openType')" name="openType">
                <ElSelect v-model="model.openType">
                  <!-- 默认 -->
                  <ElOption :value="0" :label="$t('page.manage.menu.openTypeEnum.default')" />
                  <!-- 内链 -->
                  <ElOption :value="1" :label="$t('page.manage.menu.openTypeEnum.innerChain')" />
                  <!-- 外链 -->
                  <ElOption :value="2" :label="$t('page.manage.menu.openTypeEnum.outsideChain')" />
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol :lg="12" :xs="24" v-if="model.openType == 1 || model.openType == 2">
              <ElFormItem :label="$t('page.manage.menu.href')" name="href">
                <ElInput v-model="(model.href as string)" :placeholder="$t('page.manage.menu.form.href')" />
              </ElFormItem>
            </ElCol>
            <ElCol :lg="12" :xs="12">
              <ElFormItem :label="$t('page.manage.menu.hideInMenu')" name="hideInMenu">
                <ElRadioGroup v-model="model.isHideMenu">
                  <ElRadio :value="true">{{ $t('common.yesOrNo.yes') }}</ElRadio>
                  <ElRadio :value="false">{{ $t('common.yesOrNo.no') }}</ElRadio>
                </ElRadioGroup>
              </ElFormItem>
            </ElCol>
            <ElCol :lg="12" :xs="12">
              <!-- 是否隐藏角色 -->
              <ElFormItem :label="$t('page.manage.menu.isHideRole')" name="isHideRole">
                <ElRadioGroup v-model="model.isHideRole">
                  <ElRadio :value="true">{{ $t('common.yesOrNo.yes') }}</ElRadio>
                  <ElRadio :value="false">{{ $t('common.yesOrNo.no') }}</ElRadio>
                </ElRadioGroup>
              </ElFormItem>
            </ElCol>

            <ElCol :lg="12" :xs="12">
              <!-- 是否手动添加 -->
              <ElFormItem :label="$t('page.manage.menu.isManualAdd')" name="isManualAdd">
                <ElRadioGroup v-model="model.isManualAdd">
                  <ElRadio :value="true">{{ $t('common.yesOrNo.yes') }}</ElRadio>
                  <ElRadio :value="false">{{ $t('common.yesOrNo.no') }}</ElRadio>
                </ElRadioGroup>
              </ElFormItem>
            </ElCol>


            <ElCol :lg="12" :xs="12">
              <!-- 是否开发使用 -->
              <ElFormItem :label="$t('page.manage.menu.isDeveloper')" name="isDeveloper">
                <ElRadioGroup v-model="model.isDeveloper">
                  <ElRadio :value="true">{{ $t('common.yesOrNo.yes') }}</ElRadio>
                  <ElRadio :value="false">{{ $t('common.yesOrNo.no') }}</ElRadio>
                </ElRadioGroup>
              </ElFormItem>
            </ElCol>

            <ElCol :lg="12" :xs="12">
              <!-- 是否菜单 -->
              <ElFormItem :label="$t('page.manage.menu.isMenu')" name="isMenu">
                <ElRadioGroup v-model="model.isMenu">
                  <ElRadio :value="true">{{ $t('common.yesOrNo.yes') }}</ElRadio>
                  <ElRadio :value="false">{{ $t('common.yesOrNo.no') }}</ElRadio>
                </ElRadioGroup>
              </ElFormItem>
            </ElCol>

            <ElCol :lg="12" :xs="12">
              <!-- 是否自动生成菜单 -->
              <ElFormItem :label="$t('page.manage.menu.isSystem')" name="isSystem">
                <ElRadioGroup v-model="model.isSystem">
                  <ElRadio :value="true">{{ $t('common.yesOrNo.yes') }}</ElRadio>
                  <ElRadio :value="false">{{ $t('common.yesOrNo.no') }}</ElRadio>
                </ElRadioGroup>
              </ElFormItem>
            </ElCol>

            <ElCol :lg="12" :xs="12">
              <!-- 是否需要权限 -->
              <ElFormItem :label="$t('page.manage.menu.isPermission')" name="isPermission">
                <ElRadioGroup v-model="model.isPermission">
                  <ElRadio :value="true">{{ $t('common.yesOrNo.yes') }}</ElRadio>
                  <ElRadio :value="false">{{ $t('common.yesOrNo.no') }}</ElRadio>
                </ElRadioGroup>
              </ElFormItem>
            </ElCol>
            <ElCol :span="24">
              <ElFormItem :label="$t('page.manage.menu.query')" name="query">
                <ElButton v-if="model.query.length === 0" plain block @click="addQuery(-1)">
                  <template #icon>
                    <icon-carbon-add class="align-sub text-icon" />
                  </template>
                  <span class="ml-8px">{{ $t('common.add') }}</span>
                </ElButton>
                <template v-else>
                  <div v-for="(item, index) in model.query" :key="index" class="flex gap-3">
                    <ElCol :span="9">
                      <ElFormItem :name="['query', index, 'key']">
                        <ElInput v-model="item.key" :placeholder="$t('page.manage.menu.form.queryKey')"
                          class="flex-1" />
                      </ElFormItem>
                    </ElCol>
                    <ElCol :span="9">
                      <ElFormItem :name="['query', index, 'value']">
                        <ElInput v-model="item.value" :placeholder="$t('page.manage.menu.form.queryValue')"
                          class="flex-1" />
                      </ElFormItem>
                    </ElCol>
                    <ElCol :span="5">
                      <ElSpace class="ml-12px">
                        <ElButton size='default' @click="addQuery(index)">
                          <template #icon>
                            <icon-ic:round-plus class="align-sub text-icon" />
                          </template>
                        </ElButton>
                        <ElButton size='default' @click="removeQuery(index)">
                          <template #icon>
                            <icon-ic-round-remove class="align-sub text-icon" />
                          </template>
                        </ElButton>
                      </ElSpace>
                    </ElCol>
                  </div>
                </template>
              </ElFormItem>

            </ElCol>
            <ElCol :lg="24" :xs="24">

              <ElFormItem :label="$t('page.manage.common.remark')" name="remark">
                <ElInput type="textarea" v-model="model.remark" :auto-size="{ minRows: 2, maxRows: 5 }" />
              </ElFormItem>
            </ElCol>
          </ElRow>
        </ElForm>
      </SimpleScrollbar>
    </div>
    <template #footer>
      <ElSpace justify="end" :size="16">
        <ElButton @click="closeModal">{{ $t('common.cancel') }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</ElButton>
      </ElSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
